import React, { FC, ReactElement, useCallback, useEffect, useReducer } from 'react';

import TdInput from './Input';
import TdList from './List';
import { todoReducer } from './reducer';
import { ITodo, IState, ACTION_TYPE } from './typings';

// const initialState: IState = {
//   todoList: []
// }
// 惰性初始化数据 (只能通过init方法创建数据)
function init (initTodoList: ITodo[]): IState {
  return {
    todoList: initTodoList
  }
}

const TodoList: FC = (): ReactElement => {
  // const [ todoList, setTodoList ] = useState<ITodo[]>([]);
  // useEffect(() => {
  //   console.log(todoList);
  // }, [todoList]);

  // const [ state, dispatch ] = useReducer(todoReducer, initialState)
  const [ state, dispatch ] = useReducer(todoReducer, [], init)

  useEffect(() => {
    // console.log(state.todoList)
    const todoList = JSON.parse(localStorage.getItem('todolist') || '[]')
    
    dispatch({
      type: ACTION_TYPE.INIT_TODOLIST,
      payload: todoList
    })
  }, []) // 只有一次不需要依赖项

  useEffect(() => { // 每次修改一次state.todoList时保存一次
    localStorage.setItem('todolist', JSON.stringify(state.todoList))
  }, [state.todoList])

  // 父组件传给子组件的函数 最好用 useCallback 包裹
  const addTodo = useCallback((todo: ITodo): void => {
    // setTodoList(todoList => [...todoList, todo])
    dispatch({
      type: ACTION_TYPE.ADD_TODO,
      payload: todo
    })
  }, [])

  const removeTodo = useCallback((id: number): void => {
    dispatch({ 
      type: ACTION_TYPE.REMOVE_TODO,
      payload: id
    })
  }, [])

  const toggleTodo = useCallback((id: number): void => {
    dispatch({
      type: ACTION_TYPE.TOGGLE_TODO,
      payload: id
    })
  }, [])

  return (
    <div className="todo-list">
      {/* <TdInput addTodo={ addTodo } todoList={ todoList } /> */}
      <TdInput addTodo={ addTodo } todoList={ state.todoList } />
      <TdList todoList={ state.todoList } removeTodo={ removeTodo } toggleTodo={ toggleTodo } />
    </div>
  );
}

export default TodoList;